package com.trendata.service.impl;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import com.trendata.service.IServerSocketService;
import com.trendata.util.ReturnMsg;
import com.trendata.util.SingleMessageMap;
import com.trendata.util.SingleSessionMap;

@Component("serverSocketService")
public class ServerServiceImpl implements IServerSocketService {
	private Logger logger = Logger.getLogger("serverSocketLogger");

	private static Map<String, IoSession> sessionMap;// 存储session
	private static Map<String, Object> messageMap;
	static {
		sessionMap = SingleSessionMap.getInstance();
		messageMap = SingleMessageMap.getInstance();
	}

	@Override
	public ReturnMsg<String> sendMessgaeToClientSocket(String userOpenId, String shopOpenId, String message) {
		ReturnMsg<String> resultDO = new ReturnMsg<String>();
		IoSession session = sessionMap.get(shopOpenId);
		if (session == null) {
			resultDO.setErrMsg("找不到socketClient");
			return resultDO;
		}
		// 向socket发信息
		String sendMsg = userOpenId + ":" + message;
		logger.info("user:" + userOpenId + "向服务器发送信息：" + sendMsg);
		session.write(sendMsg);
		int i = 0;
		do {
			String base64Img = (String) messageMap.get(userOpenId);
			if (base64Img == null) {
				try {
					// 一秒获取一次
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					logger.error("当sleep当前进程时出现异常：" + e.getMessage());
					e.printStackTrace();
				}
				i++;
			} else {
				messageMap.remove(userOpenId);
				resultDO.setModule(base64Img);
				resultDO.setSuccess(true);
				break;
			}
		} while (i < 20);
		if (!resultDO.isSuccess()) {
			resultDO.setErrMsg("客户socket超时未返回图片");
		}
		return resultDO;
	}
}
